package com.zengde.ai_sandbox.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zengde.ai_sandbox.dto.ChatMessage;
import com.zengde.ai_sandbox.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private ChatService chatService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        ChatMessage chatMessage = objectMapper.readValue(payload, ChatMessage.class);
        
        // 调用API获取响应
        String response = chatService.getResponse(chatMessage);
        
        // 发送响应回客户端
        session.sendMessage(new TextMessage(response));
    }
} 